package org.oos.rome;

import java.util.Random;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethodBase;

import com.sun.syndication.propono.atom.client.AuthStrategy;
import com.sun.syndication.propono.utils.ProponoException;

public class WSSEAuthStrategy implements AuthStrategy
{
	String email;
	String authToken;
	
	public WSSEAuthStrategy(String email, String authToken)
	{
		super();
		this.email = email;
		this.authToken = authToken;
	}

	@Override
	public void addAuthentication(HttpClient httpClient, HttpMethodBase method) throws ProponoException
	{
		if (email==null || authToken==null) throw new ProponoException("missing user authorization");
		
		Base64 b64 = new Base64();
		String created = new Long(System.currentTimeMillis()).toString();
		String nonce = (new Long((new Random()).nextLong())).toString();

		String digest = new String(b64.encode(DigestUtils.sha(nonce + created + authToken)));

		method.addRequestHeader("Authorization", "WSSE realm=\"11870.com\", profile=\"UsernameToken\"");
		method.addRequestHeader("X-WSSE", "UsernameToken Username=\"" + email + "\", PasswordDigest=\"" + digest + "\", Nonce=\"" + nonce + "\", Created=\"" + created + "\"");
	}
}
